package ar.edu.itba.it.paw.repo.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ar.edu.itba.it.paw.domain.Category;
import ar.edu.itba.it.paw.domain.Product;
import ar.edu.itba.it.paw.domain.Transaction;
import ar.edu.itba.it.paw.domain.exceptions.InsufficientProductsException;
import ar.edu.itba.it.paw.domain.exceptions.InvalidOperationException;
import ar.edu.itba.it.paw.repo.AbstractHibernateRepo;
import ar.edu.itba.it.paw.repo.TransactionRepo;

@Repository
public class HibernateTransactionRepo extends AbstractHibernateRepo implements TransactionRepo {

	@Autowired
	public HibernateTransactionRepo(SessionFactory sessionFactory){
		super(sessionFactory);
	}
	
	@Override
	public void buy(Transaction transaction)
			throws InsufficientProductsException, InvalidOperationException {
		if(transaction == null)
			throw new IllegalArgumentException();
		if (transaction.getBuyer().equals(transaction.getSeller())) {
			throw new InvalidOperationException();
		}

		Product product = transaction.getProduct();

		int cantDisponible = product.getQuantity();
		int cantRestante;
		/*Si esta todo bien se aade la transaccin*/
		if ((cantRestante = (cantDisponible - transaction.getQuantity())) >= 0) {
			product.updateQuantity(transaction.getQuantity());
			addTransaction(transaction);
			return;
		}
		else{
			throw new InsufficientProductsException();
		}
	}

	private void addTransaction(Transaction transaction) {
		save(transaction);
	}
	
	@Override
	public List<Transaction> getTransactionByCategory(Category category) {
		return find("from Transaction t where t.product.category = ?", category);
	}

}
